﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading.Tasks;
using System.Threading;
namespace ThreadSchedulerDemo.Winform
{
    public partial class MyForm : Form
    {
        public MyForm()
        {
            InitializeComponent();
            Text = "Synchronization Context Task Scheduler Demo";
            Visible = true;
           
            m_syncContextTaskScheduler = TaskScheduler.FromCurrentSynchronizationContext();
        }

        private readonly TaskScheduler m_syncContextTaskScheduler ;

        private CancellationTokenSource m_cts;

      

        private int Sum(CancellationToken ct, int n)
        {
            int sum = 0;
            for (; n > 0; n--)
            {
                checked { sum += n; }
                Thread.Sleep(200);
                ct.ThrowIfCancellationRequested();
            }
            return sum;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (m_cts != null)
            {
                m_cts.Cancel();
                m_cts = null;
            }
            else
            {
                Text = "Operation running";
                m_cts = new CancellationTokenSource();

                var t = new Task<int>(() => Sum(m_cts.Token, int.Parse(txtSum.Text)), m_cts.Token);
                t.Start();
                t.ContinueWith(task => txtResult.Text += "Result : " + task.Result+Environment.NewLine, CancellationToken.None, TaskContinuationOptions.OnlyOnRanToCompletion, m_syncContextTaskScheduler);


                t.ContinueWith(task => txtResult.Text += "Operation canceld"+Environment.NewLine, CancellationToken.None, TaskContinuationOptions.OnlyOnCanceled, m_syncContextTaskScheduler);

                t.ContinueWith(task => txtResult.Text += "Operation faulted"+Environment.NewLine, CancellationToken.None, TaskContinuationOptions.OnlyOnFaulted, m_syncContextTaskScheduler);
            }
        }

       
    }
}
